﻿$(async function () {
    var current = {}
    current = await initRequest()
    //左侧导航加减图片切换
    $('.checked').on('click', (e) => {
        if ($('.collapse').is('.show')) {
            $(e.target).attr("src", '../images/perfume/add.png');
            return
        } else {
            $(e.target).attr("src", '../images/perfume/reduce.png');
            return
        }
    })

    //左侧导航check图片切换
    $('.aspan').on('click', async (e) => {
        if (e.currentTarget.dataset.id == 0) {
            e.currentTarget.dataset.id = 1
            $(e.target).prev().attr("src", '../images/perfume/check.png');
            current = await initRequest()
            return
        }
        clearBtn()
        clearChecked()
        $(e.target).prev().attr("src", '../images/perfume/checked.png');
        e.currentTarget.dataset.id = 0
        current = await caretory(e.currentTarget.dataset.cate, e.currentTarget.dataset.str)
    })

    //下拉菜单(排序)
    $('.dropdown-item').on('click', (e) => {
        let str = e.currentTarget.dataset.text
        $('.btn span').html(str)
        if (str === '人气推荐') {
            hot(current)
        } else if (str === '按上市时间') {
            shoppingtime(current)
        } else if (str === '按价格从高到低') {
            priceMax(current)
        } else if (str === '按价格从低到高') {
            priceMin(current)
        } else {
            saleCount(current)
        }
    })


    $('.btnChang').on('click', async (e) => {
        if ($(e.target).is('.topa_active')) {
            $(e.target).removeClass('topa_active')
            current = await initRequest()
        } else {
            clearChecked()
            clearBtn()
            $(e.target).addClass('topa_active')
            if (e.currentTarget.dataset.name === "支持刻字") {
                current = await keepChar()
            } else {
                current = await onlyShop()
            }
        }

    })

    //重置按钮
    $('.reset').on('click', async () => {
        clearBtn()
        clearChecked()
        current = await initRequest()
    })

    //点击商品事件
    $(document).on('click', '.goodLi a', (e) => {
        getGood(e.currentTarget.dataset.id)
    })
})

//初始化加载
function initRequest() {
    return new Promise((res, rej) => {
        $.ajax({
            type: 'GET',
            url: '/getPerfumeList',
            success: (result) => {
                initLoad(JSON.parse(result))
                res(JSON.parse(result))
            }
        })
    })
}

//生成商品列表
function initLoad(result = null, current = null) {
    let str = ''
    let ps = current || result
    console.log(ps)
    for (let p in ps) {
        str += `
                <div class="col-md-3 col-6 goodLi">
                    <div class="header_img_box">
                        <span class="list_header_span">${ps[p].span}</span>
                        <a data-id="${ps[p].id}"><img src="${ps[p].img_pic}"></a>
                    </div>
                    <div class="goodLi_silder"></div>
                    <p class="goodLi-title"><a  data-id="${ps[p].id}"><span>${ps[p].EnglishName}</span></a></p>
                    <p class="goodLi-name"><a data-id="${ps[p].id}"><span class="goodLi-name_span">${ps[p].title}</span></a></p>
                    <p class="goodLi-price"><span>¥${ps[p].price}</span></p>
                    <ul class="ul">
                        <li id="salesOutFlag"><a class="topa"  data-id="${ps[p].id}"><img
                                    src="/images/perfume/shopping-fil.png"><span>${ps[p].isShop ? '立即购买' : '暂无货物'}</span></a></li>
                    </ul>
                </div>
                `
    }
    $('#content').html(str)
    if (current == null) {
        setSlider(result, getPriceMaxMin(result))
    }

}

//仅看有货
function onlyShop() {
    return new Promise((res, rej) => {
        $.ajax({
            type: 'GET',
            url: '/getPerfumeList',
            success: (result) => {
                result = JSON.parse(result)
                result = result.filter(item => item.isShop !== 0)
                initLoad(result)
                res(result)
            }
        })
    })
}

//支持刻字
function keepChar() {
    return new Promise((res, rej) => {
        $.ajax({
            type: 'GET',
            url: '/getPerfumeList',
            success: (result) => {
                result = JSON.parse(result)
                result = result.filter(item => item.span === '刻字')
                initLoad(result)
                res(result)
            }
        })
    })
}

//男士女士香水分类,系列分类
function caretory(caretoryName, str) {
    return new Promise((res, rej) => {
        $.ajax({
            type: 'GET',
            url: '/getPerfumeList',
            success: (result) => {
                result = JSON.parse(result)
                if (caretoryName === '系列') {
                    result = result.filter(item => item.sort === str)
                } else if (caretoryName === '产品分类') {
                    result = result.filter(item => item.caretory === str)
                } else {
                    result = result.filter(item => item.ml.includes(str.substring(0, str.length - 2)))
                }
                initLoad(result)
                res(result)
            }
        })
    })
}


//清空分类选择
function clearChecked() {
    let as = $('.aspan')
    for (let a of as) {
        a.dataset.id = 1
        $(a).prev().attr("src", '../images/perfume/check.png')
    }
}

//获取香水商品最大,最小价格
function getPrice() {
    return new Promise((res, rej) => {
        $.ajax({
            type: 'GET',
            url: '/getPrice',
            success: function (result) {
                res(result)
            }
        })
    })
}
//滑块组件(设置价格范围)
async function setSlider(current, price) {
    if (!price) {
        price = JSON.parse(await getPrice())
    }
    str = `
    <div class="price"><span>￥:</span><span id="left">${price[0].min}</span><span
        class="spanc">&nbsp;-</span><span>￥:</span><span id="right">${price[0].max}</span>
    </div>
    <div class="slider_input"><input data-slider-tooltip="hide" id="ex16b" type="text" /><br />
                            </div>                                                                                                                                                                                                                                                                                                                                                                                                                                                           
    `
    $('.collapseExample3').html(str)
    //滑块组件(设置价格范围)
    $("#ex16b").slider({ min: price[0].min, max: price[0].max, value: [price[0].min, price[0].max], focus: false });
    $("#ex16b").on("slide", function (slideEvt) {
        $("#left").text((slideEvt.value)[0]);
        $("#right").text((slideEvt.value)[1]);
        priceMaxMin(current, (slideEvt.value)[0], (slideEvt.value)[1])
    });
}

//清空按钮选择
function clearBtn() {
    let btns = $('.btnChang')
    for (let b of btns) {
        $(b).removeClass('topa_active')
    }
}

//人气推荐
function hot(result) {
    newResult = result.sort((a, b) => a.hot - b.hot)
    initLoad(newResult)
}

//上市时间排序
function shoppingtime(result) {
    newResult = result.sort((a, b) => new Date(a.shoppingTime) - new Date(b.shoppingTime))
    initLoad(newResult)
}

//价格升序
function priceMax(result) {
    newResult = result.sort((a, b) => b.price - a.price)
    initLoad(newResult)
}

//价格降序
function priceMin(result) {
    newResult = result.sort((a, b) => a.price - b.price)
    initLoad(newResult)
}

//销量排序
function saleCount(result) {
    newResult = result.sort((a, b) => a.saleCount - b.saleCount)
    initLoad(newResult)
}

//价格范围获取商品
function priceMaxMin(result, min, max) {
    current = result.filter(item => min <= item.price && item.price <= max)
    initLoad(result, current)
}

//获取当前商品的最大最小值
function getPriceMaxMin(result) {
    let min = result.sort((a, b) => a.price - b.price)[0].price
    let max = result.sort((a, b) => b.price - a.price)[0].price
    return [{ min, max }]
}

//获取当前商品
function getGood(id) {
    $.ajax({
        type: 'POST',
        url: '/getPerfume',
        data: { id },
        success: (result) => {
            if (!result) {
                alert('火星无法获取网络!')
                result
            }
            localStorage.setItem('good', result)
            window.location.href = '/currentGood'
        }
    })
}
